package com.itheima.reggie.controller;

import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.SetmealDish;
import com.itheima.reggie.pojo.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 购物车管理
 */
@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @PostMapping("add")
    public R<ShoppingCart> shoppingCartAdd(@RequestBody ShoppingCart shoppingCart) {
        ShoppingCart one = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .eq(shoppingCart.getDishId() != null, ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId() != null, ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .one();
        if (one != null) {
            one.setNumber(one.getNumber()+1);
            shoppingCartService.updateById(one);
            return R.success(one);
        }else {
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartService.save(shoppingCart);
            return R.success(shoppingCart);
        }
    }

    @GetMapping("list")
    public R<List<ShoppingCart>> shoppingCartList() {
        List<ShoppingCart> list = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId,BaseContext.getCurrentId())
                .list();
        return R.success(list);
    }

    @PostMapping("sub")
    public R<ShoppingCart> subShoppingCartList(@RequestBody ShoppingCart shoppingCart){
        ShoppingCart one = shoppingCartService.lambdaQuery()
                .eq(ShoppingCart::getUserId, BaseContext.getCurrentId())
                .eq(shoppingCart.getDishId()!=null,ShoppingCart::getDishId, shoppingCart.getDishId())
                .eq(shoppingCart.getSetmealId()!=null,ShoppingCart::getSetmealId, shoppingCart.getSetmealId())
                .one();
        if(one.getNumber()>1){
            one.setNumber(one.getNumber()-1);
            shoppingCartService.updateById(one);
        }else {
            shoppingCartService.removeById(one.getId());
            one.setNumber(0);
        }
        return R.success(one);

    }

    @DeleteMapping("clean")
    public R<String> clean(){
        shoppingCartService.lambdaUpdate()
                .eq(ShoppingCart::getUserId,BaseContext.getCurrentId())
                .remove();
        return R.success("清空成功");
    }
}
